(function ($) {

  function createCombobox(context, cfg) {
    $('#' + cfg.id).combobox({
      disabled: false,
      editable: false,
      panelHeight: 'auto',
      data: context.ppctData,
      valueField: 'pkid',
      textField: 'regionName',
      onSelect: function (record) {
        $('#' + context.citycfg.id).combobox({
          data: record == null ? [] : record.children,
          editable: false,
          valueField: 'pkid',
          textField: 'regionName',
          onSelect: function (_r) {
            if (_r) {
              $('#' + context.cctycfg.id).combobox({
                data: _r.children,
                editable: false,
                valueField: 'pkid',
                textField: 'regionName',
                onSelect: function (_3r) {
                  if (context.cctycfg.onSelected) {
                    context.cctycfg.onSelected(_3r);
                  }
                }

              });
              if (context.cctycfg.onSelected) {
                context.citycfg.onSelected(_r);
              }
            }
          }
        });
        $('#' + context.cctycfg.id).combobox({
          data: []
        });
        if (cfg.onSelected) {
          cfg.onSelected(record);
        }
      }
    });
  }


  function initData() {
    $province.combobox({
      editable: false,
      valueField: '',
      textField: ''
    });
    $city.combobox({
      editable: false,
      valueField: '',
      textField: ''
    });
    $area.combobox({
      editable: false,
      valueField: '',
      textField: ''
    });
  }

  function initpcctData(cfg) {
    // 树形数据
    var treeData = [];
    treeData.push({
      pkid: "",
      regionName: $.fn.combobox.defaults.emptyText
    });
    for (var p in cfg.data) {
      if (p) {
        var _d1 = cfg.data[p];
        if (_d1.level == cfg.startLevel) {
          for (var _2p in cfg.data) {
            //市级数据
            var _d2 = cfg.data[_2p];
            if (_d2.level == (cfg.startLevel + 1) && _d2.parentId == _d1.pkid) {
              if (!_d1.children) {
                _d1.children = [];
                _d1.children.push({
                  pkid: "",
                  regionName: $.fn.combobox.defaults.emptyText
                });
              }
              // 县级数据
              for (var _3p in cfg.data) {
                var _d3 = cfg.data[_3p];
                if (_d3.level == (cfg.startLevel + 2) && _d3.parentId == _d2.pkid) {
                  if (!_d2.children) {
                    _d2.children = [];
                    _d2.children.push({
                      pkid: "",
                      regionName: $.fn.combobox.defaults.emptyText
                    });
                  }
                  _d2.children.push(_d3);
                }
              }

              _d1.children.push(_d2);
            }
          }
          treeData.push(_d1);
        }
      }
    }
    $.dopcct.setting.ppctData = treeData;
    $.dopcct.setting.startLevel = cfg.startLevel;
  }

  function setValue(cfg) {
    if (cfg.val) {
      triggerSelect(cfg);
    }
  }

  function triggerSelect(cfg) {
    if (!cfg.startLevel) {
      cfg.startLevel = $.dopcct.setting.startLevel;
    }
    var val = cfg.val;
    var _cs = val.split(".");
    var $pc = $(cfg.pId);
    $pc.combobox('select', _cs[cfg.startLevel]);
    $(cfg.cId).combobox('select', _cs[cfg.startLevel + 1]);
    $(cfg.ccId).combobox('select', _cs[cfg.startLevel + 2]);
    if (cfg.oId) {
      var opts = $(cfg.oId).combobox('options');
      if (opts) {
        opts.onLoadSuccess = function () {
          cfg.onLoaded();
        };
      }
    }
  }

  $.dopcct = {
    createPcct: function (cfg) {
      var _cfg = $.extend(true, {}, $.dopcct.setting, cfg);
      createCombobox(_cfg, _cfg.pcfg);
//			createCombobox(_cfg,_cfg.citycfg);
//			createCombobox(_cfg,_cfg.cctycfg);
    },
    initpcctData: function (cfg) {
      var _cfg = $.extend(true, {}, $.dopcct.setting, cfg);
      initpcctData(_cfg);
    },
    setValue: function (cfg) {
      var _cfg = $.extend(true, {}, $.dopcct.setting.setValueSetting, cfg);
      setValue(_cfg);
    }
  };
  $.dopcct.setting = {
    CTX: '',
    data: [],
    ppctData: [],
    startLevel: 2,
    pcfg: {
      id: 'province',
      level: '2',
      url: '/region/getprovince',
      formatter: function (text, index, is, value) {
        return value + ", " + text;
      },
      onSelected: function (record) {
      }
    },
    citycfg: {
      id: 'city',
      level: '3',
      url: '/region/getchildren',
      formatter: function (text, index, is, value) {
        return value + ", " + text;
      },
      onSelected: function (record) {
      }
    },
    cctycfg: {
      id: 'county',
      level: '4',
      url: '/region/getchildren',
      formatter: function (text, index, is, value) {
        return value + ", " + text;
      },
      onSelected: function (record) {
      }
    }
  };
  $.dopcct.setting.setValueSetting = {
    val: '',
    pId: '',
    cId: '',
    ccId: '',
    oId: '',
    onLoaded: function () {
    }
  };
}(jQuery));


/**
 * 构建checkbox 和radio组件。
 * @param $
 */
(function ($) {
  /**
   * 根据目标dom取，checkbox，radio的value。
   * @param target  Dom
   * @returns {Array}
   */
  function getValue(target) {
    var dataArray = [];
    var state = $.data(target, 'ddparser');
    var items = state.options.items;
    for (var i = 0; i < items.length; i++) {
      if (items[i].checked) {
        dataArray.push($(items[i]).val());
      }
      ;
    }
    ;
    return dataArray;
  }

  /**
   * 根据目标dom设置，checkbox，radio的value。
   * @param target  目标Dom
   * @param data  设值数组
   * @returns {null}
   */
  function setValue(target, data) {
    var state = $.data(target, 'ddparser');
    var items = state.options.items;
    for (var i = 0; i < items.length; i++) {
      // $(items[i]).removeAttr('checked');
      if (typeof data == "string" || typeof data == "number") {
        if ($(items[i]).val() == data) {
          $(items[i]).attr('checked', 'checked');
        }
      } else {
        for (var j = 0; j < data.length; j++) {
          if ($(items[i]).val() == data[j]) {
            $(items[i]).attr('checked', 'checked');
          }
        }
      }
    }
    ;
  }

  function clearOtherChecked(target) {
    var state = $.data(target, 'ddparser');
    var items = state.options.items;
    for (var i = 0; i < items.length; i++) {
      $(items[i]).attr('checked', false);
    }
  }

  function clearRepulsionItemChecked(target) {
    var state = $.data(target, 'ddparser');
    var repulsionItem = state.options.repulsionItem;
    if (repulsionItem) {
      repulsionItem.attr('checked', false);
    }
  }

  function request(target, opts) {
    $(target).attr('comTagName', 'ddparser');
    create(target, opts.data);

  };
  function create(target, srcData) {
    var opts = $.data(target, 'ddparser').options;
    // 添加了数据过滤
    var data = opts.dataFilter(srcData);
    var sc = opts.splitChart || "";
    var isTextFirst = opts.isTextFirst;
    opts.items = [];
    $(target).empty();
    //var repulsionItem;
    if (opts.repulsion && data[opts.repulsion]) {
    }
    var showNum = opts.showNum - 1;
    var _self = $(target);
    for (var i = 0; i < data.length; i++) {
      var _ipt = undefined;
      if (opts.isTextFirst) {
        _self.append('&nbsp;');
        if (i != (opts.repulsion - 1)) {
          _ipt = $('<input vertical-align:middle;  tipID="' + target.id + '"  class=' + opts.validateCls
            + ' validType=' + opts.validType + ' id="bmgroup-' + data[i][opts.valueField]
            + '" name="' + opts.name + '" value="' + data[i][opts.valueField] + '" type="'
            + opts.type + '" repulsion="false"/>').appendTo(target);
        } else {
          _ipt = $('<input vertical-align:middle;  tipID="' + target.id + '" class=' + opts.validateCls
            + ' validType=' + opts.validType + '  id="bmgroup-' + data[i][opts.valueField]
            + '" name="' + opts.name + '" value="' + data[i][opts.valueField]
            + '" type="' + opts.type + '" repulsion="true"/>').appendTo(target);
        }
        if (opts.localClickName) {
          _ipt.attr('onClick', opts.localClickName + '(this)');
        }
        if (opts.unitkey) {
          _ipt.attr('unitkey', opts.unitkey);
        }
        if (opts.invalidMessage) {
          _ipt.attr('invalidMessage', opts.invalidMessage);
        }
        _self.append('&nbsp;' + data[i][opts.textField] + sc);
        if (i != 0 && i % showNum == 0) {
          _self.append('<br />');
        }
      } else {
        _self.append('&nbsp;');
        _self.append(sc + data[i][opts.textField]);
        if (i != (opts.repulsion - 1)) {
          _ipt = $('<input vertical-align:middle;   tipID="' + target.id + '" class=' + opts.validateCls
            + ' validType=' + opts.validType + '  id="bmgroup-' +
            data[i][opts.valueField] + '" name="' + opts.name + '" value="' +
            data[i][opts.valueField] + '" type="' + opts.type + '" repulsion="false"/>').appendTo(target);
        } else {
          _ipt = $('<input  vertical-align:middle;  tipID="' + target.id + '" class=' + opts.validateCls
            + ' validType=' + opts.validType + '  id="bmgroup-' +
            data[i][opts.valueField] + '" name="' + opts.name + '" value="' +
            data[i][opts.valueField] + '" type="' + opts.type + '" repulsion="true"/>').appendTo(target);
        }
        if (opts.localClickName) {
          _ipt.attr('onClick', opts.localClickName + '(this)');
        }
        if (opts.unitkey) {
          _ipt.attr('unitkey', opts.unitkey);
        }
        if (opts.invalidMessage) {
          _ipt.attr('invalidMessage', opts.invalidMessage);
        }
        if (i != 0 && i % showNum == 0) {
          _self.append('<br />');
        }
      }
      if (opts.disabled) {
        _ipt.attr('disabled', true);
      }
    }
    opts.items = $(target).children("input[repulsion=false]");
    opts.repulsionItem = $(target).children("input[repulsion=true]");
    opts.onLoadSuccess.call(target);
    bindEvent(target);
  };
  function bindEvent(target) {
    var state = $.data(target, 'ddparser');
    var repulsionItem = state.options.repulsionItem;
    var items = state.options.items;

    $(repulsionItem).bind('click', function (e) {
      state.options.onItemClick.call(repulsionItem, repulsionItem);
      if (state.options.type != 'radio') {
        clearOtherChecked(target);
      }
    });
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      $(item).bind('click', function (e) {
        state.options.onItemClick.call(this, this);
        if (state.options.type != 'radio') {
          clearRepulsionItemChecked(target);
        }
      });
    }
  };

  function reload(target, param) {
    target.innerHTML = "";
    if (typeof param.data == 'string') {
      data = $.global.getCacheObject().get(param.data);
    }
    if (param.onItemClick) {
      $.data(target, 'ddparser').options.onItemClick = param.onItemClick;
    } else {
      $.data(target, 'ddparser').options.onItemClick = function (itemNum, item) {
      };
    }

    create(target, data);
    return;
  }

  $.fn.ddparser = function (options, param) {
    if (typeof options == 'string') {
      var method = $.fn.ddparser.methods[options];
      if (method) {
        return method(this, param);
      }
    }
    options = options || {};
    return this.each(function () {
      var state = $.data(this, 'ddparser');
      if (state) {
        $.extend(state.options, options);
        request(this, state.options, {});
      } else {
        var state = $.data(this, 'ddparser', {
          options: $.extend({}, $.fn.ddparser.defaults,
            $.fn.ddparser.parseOptions(this),
            options)
        });
        request(this, state.options, {});
      }
    });
  };
  $.fn.ddparser.methods = {
    reload: function (jq, param) {
      return jq.each(function () {
        reload(this, param);
      });
    },
    attr: function (jq, param) {
      return jq.find('input').each(function () {
        for (var p in param) {
          if (p)
            $(this).attr(p, param[p]);
        }
      });
    },
    removeAttr: function (jq, param) {
      return jq.find('input').each(function () {
        $(this).removeAttr(param);
      });
    },
    disabled: function (jq, val) {
      var ipt = jq.find('input[value="' + val + '"]');
      ipt.attr('disabled', true);
    },
    disableAll: function (jq, val) {
      var ipt = jq.find('input');
      ipt.attr('disabled', true);
    },
    removeDisabled: function (jq, val) {
      var ipt = jq.find('input[value="' + val + '"]');
      ipt.removeAttr('disabled', true);
    },
    setValue: function (jq, param) {
      return setValue(jq[0], param);
    },
    getValue: function (jq) {
      return getValue(jq[0]);
    }
  };
  $.fn.ddparser.defaults = {
    // 一行展示的编码个数
    showNum: 6,
    // 缓存对象
    cacheObject: undefined,
    //input的类型 默认为checkbox
    type: 'checkbox',
    //指定数据中的第几项为排斥项
    repulsion: undefined,
    //指定分隔符
    splitChar: ',',
    textField: 'text',
    valueField: 'id',
    //指定选择框和文本描述的顺序，默认为文本在前。
    isTextFirst: true,
    // 是否禁用radio 或者 checkbox
    disabled: false,
    localClickName: '',
    // 验证样式
    validateCls: undefined,
    validType: undefined,
    unitkey: undefined,
    // 是否设置数据过滤为空。
    isFilterEmpty: false,
    // 过滤的code集合。
    filterCode: [],
    // 根据过滤条件，过滤数据。
    dataFilter: function (data) {
      var dataFilter = [];
      for (var j = 0, jlen = this.filterCode; j < jlen; j++) {
        var _tempKey = this.filterCode[j];
        for (var i = 0, len = data.length; i < len; i++) {
          if (_tempKey == data[i][this.valueField]) {
            dataFilter.push(data[i]);
          }
        }
      }
      if (this.isFilterEmpty) {
        dataFilter = [];
      }
      return dataFilter.length == 0 ? data : dataFilter;
    },
    onLoadError: function (error) {
    },
    onLoadSuccess: function () {
    },
    onItemClick: function (itemNum, item) {
    }
  };
  $.fn.ddparser.parseOptions = function (target) {
    var t = $(target);
    return {
      name: t.attr('name'),
      type: t.attr('type'),
      method: t.attr('method'),
      //url:t.attr('url'),
      bmName: t.attr('bmName'),
      textField: t.attr('textField'),
      valueField: t.attr('valueField'),
      repulsion: t.attr('repulsion'),
      splitChart: t.attr('splitChart'),
      //queryParams:eval(t.attr('queryParams')),
      dataFilter: eval(t.attr('dataFilter')),
      validateCls: t.attr('validateCls'),
      validType: t.attr('validType')
    };
  };

})(jQuery);


/**
 * 扩张combobox的请选择。
 * @param $
 */
(function ($) {
  $.fn.combobox.defaults.loader = function (_894, _895, _896) {
    var opts = $(this).combobox("options");
    if (!opts.url) {
      return false;
    }
    $.ajax({
      type: opts.method,
      url: opts.url,
      data: _894,
      dataType: "json",
      success: function (data) {
        var emptyObject = {};
        emptyObject[opts.valueField] = "";
        emptyObject[opts.textField] = $.fn.combobox.defaults.emptyText;
        data.unshift(emptyObject);
        _895(data);
      },
      error: function () {
        _896.apply(this, arguments);
      }
    });
  };
})(jQuery);


(function ($) {
  //$对象
  $.fn.easyMask = function (method, options) {
    return $.easyMask(this, method, options);
  };

  //全局函数
  $.easyMask = function (method, options) {
    var tar = 'body';
    var $targ = $(tar);
    var opt = $.extend({}, $.easyMask.options, options);
    var method = $.easyMask.methods[method];
    if (method) {
      return method(tar, opt);
    }
    return $targ;
  };
  $.easyMask.methods = {
    show: function (target, options) {
      return $(target).each(function () {
        var $targ = $(this);
        //如果当前对象不是relative,那就添加该属性
        //$("#hehe").css("position")
        if ($targ.css('position') != 'relative') {
          $targ.data('position', $targ.css('position'));
          $targ.css('position', 'relative');
        }
        $('<div class=\'datagrid-mask\' style=\"display:block;z-index:9999;\"></div>').appendTo($targ);
        var msg = $('<div class=\'datagrid-mask-msg\' style=\"display:block;left:50%;z-index:9999;\"></div>')
          .html(options.msg).appendTo($targ);
        msg.css("marginLeft", -msg.outerWidth() / 2);
      });
    },
    hide: function (target, options) {
      return $(target).each(function () {
        $here = $(this);
        $here.children('.datagrid-mask').remove();
        $here.children('.datagrid-mask-msg').remove();
        //还原position属性
        if ($here.data().position != undefined) {
          $here.css("position", $here.data().position);
          $here.removeData('position');
        }
      });
    }
  };

  $.easyMask.options = {
    msg: 'Loading...'
  };

})(jQuery);
